import os
import yaml

# 默认配置文件路径（可通过环境变量覆盖）
ROOT_PATH = os.path.dirname(__file__)
CONFIG_PATH = os.getenv("CONFIG_FILE", os.path.join(ROOT_PATH, "config.yaml"))

# 加载 YAML 配置
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
    _config = yaml.safe_load(f)


def get_config(path: str, default=None, cast_type=None):
    """
    获取配置值，支持嵌套路径，点分隔

    :param path: 如 'oss.endpoint'
    :param default: 默认值
    :param cast_type: 类型转换 如 int、bool
    :return: 配置值
    """
    keys = path.split(".")
    val = _config
    try:
        for key in keys:
            val = val[key]
    except (KeyError, TypeError):
        return default

    if cast_type:
        try:
            return cast_type(val)
        except Exception:
            return default
    return val


def get_section(section: str, default=None) -> dict:
    """
    获取整个 section 如 oss、db 对应的字典
    :param section: 一级模块名
    :return: 对应的配置 dict
    """
    return _config.get(section, default or {})